
import os
import sys
import logging
import route_conf

router_add_list = route_conf.router_add_list
router_wan_list = route_conf.router_wan_list

logging.basicConfig(level=logging.DEBUG,
                    format="[%(asctime)s %(name)s %(levelname)s %(lineno)d] %(message)s",
                    datefmt='%Y-%m-%d %H:%M:%S'
                    )

file_path = 'D:\jz_works\jz_data\jz_shell\cmd_handle_router_py3'
run_bin = file_path + '\\venv\Scripts'


def wan(t=1):
    logging.info('开始更新网关路由条目...')
    check_version()
    for router in router_wan_list:
        logging.info("处理路由:")
        logging.info(router)
        logging.info(os.popen(router).read())
    logging.info(os.popen('route print').read())
    timeout_new(t)

def update(t=1):
    logging.info('开始更新路由条目...')
    clear(1)
    add(1)
    timeout_new(t)

def update_all(t=1):
    logging.info('开始更新路由条目...')
    clear(1)
    add(1)
    wan(1)
    timeout_new(t)

def clear(t=1):
    logging.info('开始清理路由条目...')
    check_version()
    check_build_dir(t=3)
    import time
    time.sleep(3)
    for router in check_router_list(router_add_list):
        logging.info("清理路由: {}".format(router))
        list = router.split(' ')
        router_clear = "{} delete {} {} {}".format(list[0], list[2], list[3], list[4])
        logging.info(router_clear)
        logging.info(os.popen(router_clear).read())

    show_router()
    timeout_new(t)

def add(t=1):
    logging.info('开始添加路由条目...')
    check_version()
    check_build_dir(t=3)

    for router in check_router_list(router_add_list):
        logging.info("添加路由:")
        logging.info(router)
        logging.info(os.popen(router).read())

    show_router()
    timeout_new(t)

def show_router(t=1):
    logging.info('route print')
    check_version()
    logging.info(os.popen('route print').read())
    timeout_new(t)

def create_exe(t=1):
    logging.info('开始创建EXE...')
    check_version()

    logging.info("项目目录：{}".format(file_path))
    os.chdir(file_path)
    logging.info("进入目录：{}".format(file_path))

    check_build_dir(t=3)

    logging.info("激活 ENV...{}\\activate".format(run_bin))
    timeout_new(3)

    logging.info(os.system('{}\\activate'.format(run_bin)))
    logging.info(os.popen('{}\python --version'.format(run_bin)).read())
    timeout_new(1)

    for p in ['route_add.py', 'route_delete.py', 'route_update.py', 'route_update_all.py', 'route_show_router.py']:
        logging.info("开始打包[{}]...{}\pyinstaller --uac-admin --clean -F {}".format(p, run_bin, p))
        # logging.info(os.popen('{}\pyinstaller --uac-admin --clean -F {}'.format(run_bin, p)).read())
        logging.info(os.popen('{}\python -O -m PyInstaller --uac-admin --clean -F {}'.format(run_bin, p)).read())

    logging.info("关闭 ENV...{}\deactivate".format(run_bin))
    logging.info(os.system('{}\deactivate'.format(run_bin)))
    timeout_new(t)

def check_build_dir(t=1):
    logging.info("清理build目录...")
    if os.path.exists(os.path.join(file_path, 'build')):
        import shutil
        shutil.rmtree(os.path.join(file_path, 'build'))
        logging.info("删除目录 ...{}".format(os.path.join(file_path, 'build')))

def check_version():
    if sys.version_info[0] == 2 and sys.version_info[1] < 7:
        logging.error("请使用python3.7及以上的版本运行，当前[{}]".format(sys.version_info[:3]))
        sys.exit()

def check_router_list(list):
    new_list = []
    error_list = []
    import re
    for r in list:
        sb = re.sub('\s|\t|\n', ' ', r)
        sp = sb.split(' ')
        nlist = [i for i in sp if i != '']
        if len(nlist) < 6:
            error_list.append(r)
            continue

        new_list.append(r)
    if len(error_list) > 0:
        logging.error("路由条目配置错误，请检查[{}]".format(error_list))
        timeout_new(5)
        sys.exit()
    return new_list

def timeout_new(t=1):
    logging.info('sleep {}s'.format(t))
    logging.info(os.popen('timeout /T {}'.format(t)).read())
